<template>
  <div class="login-page">
    <el-card>
      <template #header>面经运营后台</template>
      <el-form :model="form" :rules="rules" label-width="auto" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" show-password v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item class="tc">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'LoginIndex',
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { pattern: /^[a-zA-Z0-9]{5,11}$/, message: '请输入5到11位的密码', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    async login () {
      try {
        // 如果验证成功，返回值是 true
        await this.$refs.form.validate()
        // action是异步的，await表示拿到结果了，再进行下面的代码
        await this.$store.dispatch('user/loginAction', this.form)
        this.$message.success('登录成功~')
        this.$router.push('/')
      } catch (e) {
        // e可以捕获try代码块中，await出错时的错误
        // 如果验证的错误，打印未通过校验的字段
        // 如果是登录账号密码的错误，会打印错误的请求。这类错误在响应拦截器里处理
        console.log(e)
      }
    },
    reset () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header{
      height: 80px;
      background: rgba(114,124,245,1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}

</style>
